#include "engine.h"
#include "file.h"
#include <sys/stat.h>

file_t::file_t()
{
	f=NULL;
	size=0;
}

file_t::file_t(const char* filename,const char* mode)
{
	f=fopen(filename,mode);

	if (f)
	{
		struct stat statistics;
		fstat(_fileno(f),&statistics);
		size=statistics.st_size;
	}
}

bool file_t::open(const char* filename, const char* mode)
{
	f=fopen(filename,mode);

	if (f)
	{
		struct stat statistics;
		fstat(_fileno(f),&statistics);
		size=statistics.st_size;
	}

	return f!=NULL;
}

void file_t::read(void * dst, uint32 numbytes)
{
	fread(dst,1,numbytes,f);
}

void file_t::write(const void* str,int len)
{
	fwrite(str,1,len,f);
}

void file_t::writestring(const char* str)
{
	fwrite(str,1,strlen(str),f);
}

void file_t::writestring(const string& str)
{
	fwrite(str.c_str(),1,str.size(),f);
}

void file_t::close()
{
	if (f)
	{
		fclose(f);
		f=NULL;
		size=0;
	}
}

file_t::~file_t()
{
	close();
}